<template>
  <el-dialog
    width="1400"
    :title="'打卡活动' + dialogTitle"
    v-model="visible"
    draggable
    @close="closeDialog"
  >
    <el-scrollbar ref="scrollRef" height="700px" :min-size="10">
      <div style="display: flex">
        <miniAppBox
          ref="miniAppBoxRef"
          :tableData="tableData"
          :buttonName="formParams.buttonName"
          :backgroundImg="handleImgChange('backgroundImg')"
          :checkedIcon="handleImgChange('checkedIcon')"
          :uncheckedIcon="handleImgChange('uncheckedIcon')"
        />
        <div class="main">
          <div class="title">基本设置</div>
          <el-form
            :disabled="dialogTitle.includes('详情')"
            :model="formParams"
            ref="formRef"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="活动名称" prop="name">
              <el-input
                v-model.trim="formParams.name"
                placeholder="请输入活动名称，最多10字"
                maxlength="10"
                clearable
                style="width: 240px"
              />
            </el-form-item>

            <el-form-item label="活动时间" prop="time">
              <div>
                <el-date-picker
                  v-model="formParams.time"
                  type="daterange"
                  format="YYYY-MM-DD"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                />
              </div>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model.trim="formParams.remark"
                placeholder="最多20字"
                maxlength="20"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <div class="title">活动设置</div>

            <el-form-item label="上传背景" prop="backgroundImg">
              <!-- :imagePx="[750, 974]" -->
              <ImageUploadByType
                v-model="formParams.backgroundImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                :imagePx="[750, 974]"
              />
              <div>图片比例为750px*974px，请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件</div>
            </el-form-item>

            <el-form-item label="按钮文字" prop="buttonName">
              <el-input
                v-model.trim="formParams.buttonName"
                placeholder="请输入按钮文字，最多10字"
                maxlength="10"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="使用规则" prop="activityRule">
              <div style="width: 100%">
                <el-input
                  v-model="formParams.activityRule"
                  style="width: 300px"
                  :autosize="{ minRows: 3, maxRows: 8 }"
                  type="textarea"
                  maxlength="1000"
                  placeholder="请输入内容"
                  show-word-limit
                />
              </div>
            </el-form-item>

            <div class="title">打卡规则 <span class="tips">打卡规则最多可配置12单</span></div>
            <div class="el_table" style="margin-bottom: 20px">
              <el-table :data="tableData">
                <el-table-column
                  align="center"
                  prop="name"
                  label="奖品名称"
                  show-overflow-tooltip
                  width="100"
                >
                  <template #default="{ $index, row }">
                    <el-link
                      :disabled="dialogTitle.includes('详情')"
                      :underline="false"
                      type="primary"
                      @click="handleShowList($index)"
                      >{{ row.name || '点击添加奖品' }}</el-link
                    >
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="rewardType" label="奖品类型">
                  <template #default="{ row }">
                    {{
                      row.rewardType === 3
                        ? '实物券'
                        : row.rewardType === 2
                        ? '礼包'
                        : row.rewardType
                        ? '优惠券'
                        : ''
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="totalInventory"
                  label="活动总库存"
                  width="130px"
                >
                  <template #header>
                    <div><span style="color: red">*</span>活动总库存</div>
                  </template>
                  <template #default="{ row }">
                    <div :class="!row.totalInventory ? 'empty' : ''">
                      <el-input-number
                        style="width: 90px"
                        :controls="false"
                        v-model="row.totalInventory"
                        :min="row.totalInventory ? 1 : 0"
                        :max="row.surplusCount ? row.surplusCount : 9999999"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="residualInventory" label="剩余库存" />

                <el-table-column align="center" prop="rules" label="满N单" width="110px">
                  <template #header>
                    <span style="color: red">*满N单</span>
                  </template>
                  <template #default="{ $index, row }">
                    <div :class="!row.rules ? 'empty' : ''">
                      <el-input-number
                        @blur="handleRulesBlur(row, $index)"
                        style="width: 90px"
                        :controls="false"
                        v-model="row.rules"
                        :min="1"
                        :max="12"
                      />
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  align="center"
                  prop="rewardImageUrl"
                  label="奖品缩略图"
                  width="130"
                >
                  <template #header>
                    <div><span style="color: red">*</span>奖品缩略图</div>
                  </template>
                  <template #default="{ row }">
                    <div
                      :class="!row.rewardImageUrl ? 'empty' : ''"
                      style="display: flex; flex-direction: column; align-items: center"
                    >
                      <!--  :imagePx="[204, 148]" -->
                      <ImageUploadByType
                        v-model="row.rewardImageUrl"
                        custom
                        :isShowTip="false"
                        uploadType="1"
                        :limit="1"
                        :fileSize="10"
                        :imagePx="[204, 148]"
                      />204px*148px 1M
                      <div style="color: red" v-show="!row.rewardImageUrl">请上传奖品缩略图</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="popupImageUrl" label="通知弹窗" width="130">
                  <template #header>
                    <div><span style="color: red">*</span>通知弹窗</div>
                  </template>
                  <template #default="{ row }">
                    <div
                      :class="!row.popupImageUrl ? 'empty' : ''"
                      style="display: flex; flex-direction: column; align-items: center"
                    >
                      <!--  :imagePx="[592, 840]" -->
                      <ImageUploadByType
                        v-model="row.popupImageUrl"
                        custom
                        :isShowTip="false"
                        uploadType="1"
                        :limit="1"
                        :fileSize="10"
                        :imagePx="[592, 840]"
                      />592px*840px 1M
                      <div style="color: red" v-show="!row.popupImageUrl">请上传通知弹窗</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" fixed="right">
                  <template #default="scope">
                    <el-button
                      icon="Minus"
                      v-show="tableData.length > 1"
                      circle
                      @click.prevent="deleteRow(scope.$index)"
                    >
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button v-show="tableData.length < 12" style="width: 100%" @click="onAddItem">
                添加
              </el-button>
            </div>

            <div class="title">打卡icon</div>
            <el-form-item class="_el-radio-group" label="已打卡icon" prop="checkedIconVal">
              <el-radio-group
                @change="(val) => handleIconImgChange(val, 1)"
                v-model="formParams.checkedIconVal"
              >
                <el-radio :value="0" :label="0" size="large">
                  默认图标
                  <br />
                  <el-image
                    style="width: 100px; height: 70px"
                    src="https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/1icon.png"
                  />
                </el-radio>
                <br />
                <el-radio :value="1" :label="1" size="large">
                  自定义图标
                  <ImageUploadByType
                    v-show="formParams.checkedIconVal == 1"
                    v-model="formParams.checkedIcon"
                    :isShowTip="false"
                    uploadType="1"
                    :limit="1"
                    :fileSize="1"
                    :imagePx="[116, 84]"
                  />
                  <!-- :imagePx="[116px, 84]" -->
                  <div class="upload-tip" v-show="formParams.checkedIconVal == 1"
                    >图片比例为116px*84px，请上传 大小不超过 1MB 格式为 png/jpg/jpeg 的文件</div
                  >
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="_el-radio-group" label="未打卡icon" prop="uncheckedIconVal">
              <el-radio-group
                @change="(val) => handleIconImgChange(val, 0)"
                v-model="formParams.uncheckedIconVal"
              >
                <el-radio :value="0" :label="0" size="large">
                  默认图标
                  <br />
                  <el-image
                    style="width: 100px; height: 70px"
                    src="https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/0icon.png"
                  />
                </el-radio>
                <br />
                <el-radio :value="1" :label="1" size="large">
                  自定义图标
                  <ImageUploadByType
                    v-show="formParams.uncheckedIconVal == 1"
                    v-model="formParams.uncheckedIcon"
                    :isShowTip="false"
                    uploadType="1"
                    :limit="1"
                    :fileSize="1"
                    :imagePx="[116, 84]"
                  />
                  <!-- :imagePx="[116px, 84]" -->
                  <div class="upload-tip" v-show="formParams.uncheckedIconVal == 1"
                    >图片比例为116px*84px，请上传 大小不超过 1MB 格式为 png/jpg/jpeg 的文件</div
                  >
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <div class="title">分享设置</div>
            <el-form-item label="分享标题" prop="shareTitle">
              <el-input
                v-model.trim="formParams.shareTitle"
                placeholder="请输入标题名称，最多20字"
                maxlength="20"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="上传图片" prop="shareImg">
              <div
                ><ImageUploadByType
                  v-model="formParams.shareImg"
                  :isShowTip="false"
                  uploadType="1"
                  :limit="1"
                  :fileSize="10"
                  validateAspectRatio5To4
                />
                <!-- :imagePx="[500, 400]" -->
                请上传 大小不超过 10MB 格式为 png/jpg/jpeg 的文件 图片的比例为5:4, 如500px*400px
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-scrollbar>

    <template #footer v-if="!dialogTitle.includes('详情')">
      <el-button type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>

    <couponList ref="couponListRef" @select="handleSelect" />
  </el-dialog>
</template>
<script setup>
import { getPunchCardDetailsApi, postAddPunchCardApi } from '@/api/marketing/punchCard'
import { formatTexarea, parseTime } from '@/utils/tools'
import miniAppBox from './miniAppBox.vue'
import couponList from './couponList.vue'

const { proxy } = getCurrentInstance()
const visible = ref(false)
const dialogTitle = ref('详情')
const formParams = ref({
  name: null,
  remark: null,
  time: null,
  backgroundImg: null,
  buttonName: null,
  activityRule: null,
  shareTitle: null,
  shareImg: null,
  checkedIconVal: null,
  uncheckedIconVal: null,
  checkedIcon: null,
  uncheckedIcon: null,
  cityName: null
})
const formRef = ref()
const couponListRef = ref()
const tableData = ref([])
const miniAppBoxRef = ref()
function checkUncheckedIconVal(rule, value, callback) {
  setTimeout(() => {
    if (formParams.value.uncheckedIconVal) {
      if (!formParams.value.uncheckedIcon || formParams.value.uncheckedIcon.length == 0) {
        return callback(new Error('请上传'))
      }
      callback()
    } else {
      if (formParams.value.uncheckedIconVal == 0) {
        return callback()
      }
      callback(new Error('请选择'))
    }
  }, 500)
}
function checkIconVal(rule, value, callback) {
  console.log(formParams.value.checkedIconVal, formParams.value.checkedIcon)
  setTimeout(() => {
    if (formParams.value.checkedIconVal) {
      if (!formParams.value.checkedIcon || formParams.value.checkedIcon.length == 0) {
        return callback(new Error('请上传'))
      }
      callback()
    } else {
      if (formParams.value.checkedIconVal == 0) {
        return callback()
      }
      callback(new Error('请选择'))
    }
  }, 500)
}
const rules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  time: [{ required: true, message: '请选择用券时间', trigger: 'change' }],
  backgroundImg: [{ required: true, message: '请上传背景图', trigger: 'blur' }],
  buttonName: [{ required: true, message: '请输入按钮文字', trigger: 'blur' }],
  activityRule: [{ required: true, message: '请输入使用规则', trigger: 'blur' }],
  shareTitle: [{ required: true, message: '请输入分享标题', trigger: 'blur' }],
  shareImg: [{ required: true, message: '请上传分享图片', trigger: 'blur' }],
  checkedIconVal: [{ required: true, validator: checkIconVal, trigger: ['change', 'blur'] }],
  uncheckedIconVal: [
    { required: true, validator: checkUncheckedIconVal, trigger: ['change', 'blur'] }
  ]
}
// 监听图片是否上传的校验
watch(
  () => [formParams.value.checkedIcon, formParams.value.uncheckedIcon],
  () => {
    if (formParams.value.checkedIconVal == 1) {
      formRef.value.validateField('checkedIconVal')
    }

    if (formParams.value.uncheckedIconVal == 1) {
      formRef.value.validateField('uncheckedIconVal')
    }
  },
  { immediate: false } // 避免初始渲染时触发
)

function handleCheckList() {
  const noDataItem = tableData.value.find(
    (i) =>
      !i.distributionQuantity ||
      !i.name ||
      !i.popupImageUrl ||
      !i.residualInventory ||
      !i.rewardId ||
      !i.rewardImageUrl ||
      !i.rewardType ||
      !i.rules ||
      !i.totalInventory
  )
  if (noDataItem) {
    ElMessage.warning('校验打卡规则列表数据！')
    return false
  }
  return true
}
function handleAction(confirm) {
  console.log(formParams.value.cityName)
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid && handleCheckList()) {
        console.log('formParams', formParams.value)
        if (!formParams.value.cityName) ElMessage.error('城市名称获取为空')
        const params = {
          ...formParams.value,
          activityRule: formatTexarea(formParams.value.activityRule),
          startTime: formParams.value.time.length ? formParams.value.time[0] : '',
          endTime: formParams.value.time.length ? formParams.value.time[1] : '',
          backgroundImg: formParams.value.backgroundImg.length
            ? formParams.value.backgroundImg[0].url
            : '',
          uncheckedIcon:
            Array.isArray(formParams.value.uncheckedIcon) && formParams.value.uncheckedIcon.length
              ? formParams.value.uncheckedIcon[0].url
              : formParams.value.uncheckedIcon,
          checkedIcon:
            Array.isArray(formParams.value.checkedIcon) && formParams.value.checkedIcon.length
              ? formParams.value.checkedIcon[0].url
              : formParams.value.checkedIcon,
          shareImg: formParams.value.shareImg.length ? formParams.value.shareImg[0].url : '',
          activitySignInsRulesList: tableData.value.map((i) => {
            return {
              ...i,
              rewardImageUrl: i.rewardImageUrl.length ? i.rewardImageUrl[0].url : '',
              popupImageUrl: i.popupImageUrl.length ? i.popupImageUrl[0].url : ''
            }
          })
        }
        console.log({ params })
        delete params.time
        delete params.checkedIconVal
        delete params.uncheckedIconVal
        postAddPunchCardApi(params).then((res) => {
          if (res.code == 200) {
            emit('refresh')
            closeDialog()
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  } else {
    closeDialog()
  }
}
function deleteRow(index) {
  tableData.value.splice(index, 1)
}
const curIndex = ref(null)
function handleShowList(index) {
  curIndex.value = index
  couponListRef.value.init([tableData.value[index]], formParams.value.cityName)
}
/** 触发优惠券满N单规则 */
function handleRulesBlur(row, index) {
  if (tableData.value[index - 1]?.rules && tableData.value[index - 1]?.rules >= row?.rules) {
    tableData.value[index].rules = null
    ElMessage.warning(`请输入比第${index}条数据的满N单大的数字`)
  } else if (tableData.value[index + 1]?.rules && tableData.value[index + 1]?.rules <= row?.rules) {
    tableData.value[index].rules = null
    ElMessage.warning(`请输入比第${index + 2}条数据的满N单小的数字`)
  }
}
/**小程序图片切换 */
function handleImgChange(val) {
  const value = formParams.value[val]
  if (Array.isArray(value) && value.length > 0) {
    return value[0].url
  } else {
    return value
  }
}
/**icon选择变化 */
function handleIconImgChange(val, type) {
  if (type) {
    formParams.value.checkedIcon = val
      ? ''
      : 'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/1icon.png'
  } else {
    formParams.value.uncheckedIcon = val
      ? ''
      : 'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/0icon.png'
  }
  console.log(formParams.value.checkedIcon, formParams.value.uncheckedIcon)
}
function onAddItem() {
  tableData.value.push({
    name: null,
    rewardType: null,
    rewardId: null,
    totalInventory: null,
    surplusCount: null,
    residualInventory: null,
    distributionQuantity: null,
    rewardImageUrl: null,
    popupImageUrl: null
  })
}
function closeDialog() {
  formRef.value.resetFields()
  formParams.value.uncheckedIcon = null
  formParams.value.checkedIcon = null
  visible.value = false
  tableData.value = []
  miniAppBoxRef.value.handleSwitching()
}
/**获取优惠券信息 */
function handleSelect(val) {
  console.log({ val })
  tableData.value[curIndex.value] = {
    name: val?.name,
    rewardType: val.type === 6 ? 3 : val.type === 88 ? 2 : 1,
    rewardId: val.id,
    totalInventory: val.surplusCount,
    surplusCount: val.surplusCount,
    residualInventory: val.surplusCount,
    distributionQuantity: val?.grantNum
  }
  console.log(tableData.value)
}
/**初始化详情接口数据 */
function initData(data) {
  if (!data) return
  formParams.value = {
    name: data?.name,
    remark: data?.remark,
    time: [parseTime(data?.startTime), parseTime(data?.endTime)],
    backgroundImg: data?.backgroundImg,
    buttonName: data?.buttonName,
    activityRule: formatTexarea(data?.activityRule, 1),
    shareTitle: data?.shareTitle,
    shareImg: data?.shareImg,
    checkedIcon: data?.checkedIcon,
    uncheckedIcon: data?.uncheckedIcon,
    checkedIconVal:
      data?.checkedIcon === 'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/1icon.png'
        ? 0
        : 1,
    uncheckedIconVal:
      data?.uncheckedIcon ===
      'https://qafanle.oss-cn-hangzhou.aliyuncs.com/img/2025/01/02/0icon.png'
        ? 0
        : 1
  }
  tableData.value = data?.activitySignInsRulesVOList?.map((i) => ({ ...i, name: i.rewardName }))
  console.log(tableData.value)
}
function init(row, title, cityName) {
  if (title === 'edit') {
    dialogTitle.value = '编辑'
  } else if (title === 'add') {
    formParams.value.cityName = cityName
    console.log('新增', formParams.value.cityName)
    dialogTitle.value = '新增'
  } else {
    dialogTitle.value = '详情'
    getPunchCardDetailsApi(row.id).then((res) => {
      initData(res?.data)
    })
  }
  visible.value = true
}
const emit = defineEmits(['refresh'])
defineExpose({
  init
})
</script>
<style lang="scss" scoped>
.title {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  .tips {
    margin-left: 10px;
    font-size: 14px;
  }
}
.main {
  margin-left: 50px;
}

._el-radio-group {
  min-height: 310px !important;
  ::v-deep(.el-radio-group) {
    display: flex;
    flex-direction: column;
    align-items: start;
    justify-content: space-between;
    min-height: 150px !important;
  }
  ::v-deep(.el-radio) {
    display: block;
  }
  ::v-deep(.el-form-item__content) {
    display: block !important;
  }
  .upload-tip {
    color: rgb(96, 98, 102) !important;
    font-family:
      Helvetica Neue,
      Helvetica,
      PingFang SC,
      Hiragino Sans GB,
      Microsoft YaHei,
      Arial,
      sans-serif;
  }
}
:deep(.empty .el-input__wrapper) {
  border: 1px solid red;
}
</style>
